package com.eqdd.yiqidian.ui.yiqixue.fragment;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.eqdd.yiqidian.CoolRefreshRecyclerViewFragmentCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.HttpResultRows;
import com.eqdd.yiqidian.bean.rebuild.LearnVideoListBean;
import com.eqdd.yiqidian.box.span.MovementMethod.ClickMovementMethod;
import com.eqdd.yiqidian.box.span.TagSpan;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.yiqixue.LearnSearchActivity;
import com.eqdd.yiqidian.utils.ImagePauseLoadUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;

/**
 * @author吕志豪 .
 * @date 18-2-7  下午2:12.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class FindVideoFragment extends BaseFragment {
    private CoolRefreshRecyclerViewFragmentCustom dataBinding;
    private SlimAdapterEx<LearnVideoListBean> slimAdapterEx;
    private int pageNum;
    private String query;
    private MVCCoolHelper<List<LearnVideoListBean>> mvcHelper;
    private String url;
    private String field;

    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        return dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_cool_recycler_view, null, false);
    }

    @Override
    protected void initData() {
        if (slimAdapterEx == null) {
            url = TextUtils.isEmpty(url) ? getArguments().getString(Config.URL) : url;
            String lectureGuid = getArguments().getString(Config.LECTURE_GUID);
            dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            ImagePauseLoadUtil.pauseLoad(this, dataBinding.recyclerView);
            //添加自定义分割线
            DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
            dataBinding.recyclerView.addItemDecoration(divider);
            slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_112, new SlimInjector<LearnVideoListBean>() {
                @Override
                public void onInject(LearnVideoListBean data, IViewInjector injector) {

                    injector.image(R.id.iv_poster, data.getVideoImage())
                            .text(R.id.tv_title, data.getVideoTitle())
                            .text(R.id.tv_time, data.getVideoTime())
                            .with(R.id.tv_types, view -> {
                                TextView textView = (TextView) view;
                                textView.setText("");
                                String[] split = data.getLabel().split(",");
                                for (String s : split) {
                                    SpannableString spanString = new SpannableString(s);
                                    TagSpan tagSpan = new TagSpan(Color.GREEN, 10, 10);
                                    tagSpan.setTextClick(text -> {
                                        Bundle bundle = new Bundle();
                                        bundle.putInt(Config.POS, 2);
                                        bundle.putString(Config.FIELD, text.toString());
                                        startActivity(LearnSearchActivity.class, bundle);

                                    });
                                    spanString.setSpan(tagSpan, 0, s.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                                    textView.append(spanString);
                                }
                                textView.setMovementMethod(ClickMovementMethod.getInstance());
                            });
                }
            }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
            ItemClickSupport.addTo(dataBinding.recyclerView)
                    .setOnItemClickListener((recyclerView, position, v) -> {
                       /* Bundle bundle = new Bundle();
                        bundle.putString(Config.URL, slimAdapterEx.getDataItem(position).getVideoUrl());
                        bundle.putString(Config.CONTENT, slimAdapterEx.getDataItem(position).getDescribe());
                        startActivity(YoukuPlayActivity.class, bundle);*/
                    });
            ModelRx2DataSource<LearnVideoListBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
                @Override
                public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                    pageNum = page == 1 ? 0 : pageNum;
                    return OkGo.<HttpResultRows<LearnVideoListBean>>post(HttpConfig.BASE_URL + url)
                            .params("page", pageNum)
                            .params("para", query)
                            .params("type", field)
                            .params("lectureGuid", lectureGuid)
                            .converter(new JsonConverter<HttpResultRows<LearnVideoListBean>>() {
                                @Override
                                public void test() {
                                    super.test();
                                }
                            }).adapt(new FlowableBody<>())
                            .flatMap(listResultBean -> {
                                pageNum = listResultBean.getItems().getPage();
                                if (listResultBean.getStatus() == 200) {
                                    return Flowable.just(listResultBean.getItems() == null ? new ArrayList<LearnVideoListBean>() : listResultBean.getItems().getRows());
                                } else {
                                    ToastUtil.showShort(listResultBean.getMsg());
                                    return Flowable.just(new ArrayList<>());
                                }
                            });

                }
            });
            slimAdapterEx.updateData(new ArrayList<>());
            mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
            mvcHelper.setDataSource(dataSource);
            mvcHelper.setAdapter(slimAdapterEx);
            if (!TextUtils.isEmpty(url)) {
                mvcHelper.refresh();
            }
        }
    }

    @Override
    protected void setView() {

    }

    @Override
    public void onClick(View v) {

    }

    public void refresh(CharSequence currentQuery) {
        query = (String) currentQuery;
        mvcHelper.refresh();
    }

    public void refresh(String url, CharSequence currentQuery) {
        this.url = url;
        query = (String) currentQuery;
        if (mvcHelper != null) {
            mvcHelper.refresh();
        }
    }

    public void filed(String url, String field) {
        this.url = url;
        this.field = field;
        if (mvcHelper != null) {
            mvcHelper.refresh();
        }
    }
}
